package com.qst.order.config;

import com.qst.order.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil; // 你的 JWT 工具类

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        // 1. 跳过 OPTIONS 请求
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            filterChain.doFilter(request, response);
            return;
        }
        // 2. 跳过登录/注册接口（无需 Token 验证）



        // 1. 从请求头提取 Token
        String token = resolveToken(request);

        // 2. 如果 Token 存在且有效，设置 Authentication 到 SecurityContext
        if (token != null && jwtUtil.verifyToken(token)) {
            String userId =(String) jwtUtil.getClaim(token,"userId");
            UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(userId, null, Collections.emptyList());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        // 3. 继续执行过滤器链
        filterChain.doFilter(request, response);
    }

    // 从请求头提取 Token

    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        //System.out.println("---------"+bearerToken);
        if (bearerToken != null ) {
            return bearerToken;
        }
        return null;
    }
}